package com.contactbook.web.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.AccountClient;
import contactbook.model.Account;

public class LoginController extends HttpServlet implements Servlet {
	
	private static final long serialVersionUID = 1L;
	
	private static final String CONFIRM_LOGIN = "OK";
	private static final String LOGOUT = "logout";
	
	private AccountClient accountClient;
   
    public LoginController() {
        super();
        accountClient = new AccountClient();
    }
    
    public void init() throws ServletException {
    	super.init();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		String submit = request.getParameter("submit");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		
		if (submit == null) {
			dispatcher = request.getRequestDispatcher("/login.jsp");
		}
		
		else if (submit.equals(CONFIRM_LOGIN)) {
			if (account == null) {
				String login = request.getParameter("login");
				String password = request.getParameter("password");
				if (!login.equals("") && !password.equals("")) {
					account = accountClient.login(login, password);
					if (account != null)
			        	session.setAttribute("account", account);
				}
			}
		}
		
		else if (submit.equals(LOGOUT)) {
			accountClient.logout();
			session.removeAttribute("account");
			session.invalidate();
		}
		
		dispatcher.forward(request, response);
	}
	
	public void destroy() {
		super.destroy();
	}
}
